<?php declare(strict_types=1);
/**
 * This file is part of Swoft.
 *
 * @link     https://swoft.org
 * @document https://swoft.org/docs
 * @contact  group@swoft.org
 * @license  https://github.com/swoft-cloud/swoft/blob/master/LICENSE
 */

namespace App\Model\Logic;

use Exception;
use Swoft\Bean\Annotation\Mapping\Bean;
use Swoft\Bean\Annotation\Mapping\Inject;
use Swoft\Breaker\Annotation\Mapping\Breaker;
use Swoft\Redis\Pool;

/**
 * Class BreakerLogic
 *
 * @since 2.0
 *
 * @Bean()
 */
class BreakerLogic
{
    /**
     * @Inject()
     * @var Pool
     */
    private $redis;

    /**
     * @Breaker(
     *     fallback="funcFallback",
     *     timeout=1.0,
     *     failThreshold=3,
     *     sucThreshold=6,
     *     retryTime=60
     *     )
     * @return string
     * @throws Exception
     */
    public function func(): string
    {
        $count = $this->redis->get('count');
        if ($count === false){
            $count = 1;
        }
        var_dump('hello func' . $count);
        $this->redis->set('count', $count+1);
        if ($count <= 3) {// 失败尝试,3次以后应该不能直接调用这个方法
            throw new Exception('Breaker exception');
        }
        // php -d phar.readonly=0 /Users/xiao/Desktop/php-swoft/swoftcli.phar phar:pack -o=swoft-order.phar
        return 'success?????';
    }

    /**
     * @return string
     */
    public function funcFallback(): string
    {
        var_dump('funcFallback');
        return 'funcFallback';
    }


    /**
     * @Breaker()
     *
     * @return string
     * @throws Exception
     */
    public function func2(): string
    {
        // Do something

        return 'func2';
    }



    /**
     * @Breaker(fallback="loopFallback")
     *
     * @return string
     * @throws Exception
     */
    public function loop(): string
    {
        // Do something

        throw new Exception('Breaker exception');
    }

    /**
     * @Breaker()
     *
     * @return string
     * @throws Exception
     */
    public function unFallback(): string
    {
        // Do something

        throw new Exception('Breaker exception');
    }

    /**
     * @Breaker(fallback="loopFallback2")
     *
     * @return string
     * @throws Exception
     */
    public function loopFallback(): string
    {
        // Do something

        throw new Exception('Breaker exception');
    }

    /**
     * @Breaker(fallback="loopFallback3")
     *
     * @return string
     * @throws Exception
     */
    public function loopFallback2(): string
    {
        // Do something

        throw new Exception('Breaker exception');
    }

    /**
     * @return string
     */
    public function loopFallback3(): string
    {
        return 'loopFallback3';
    }
}
